local UIBase = require("view.UIBase")
local MonsterHoleView = class("MonsterHoleView", UIBase)
local monsterhole = require("config.monsterhole")
local DropHelper = require("data.helper.DropHelper")

function MonsterHoleView:ctor()
    local resource = {
        path = "Prefabs/View/MonsterHole",
        name = "MonsterHoleView",
        canvas = 2
    }
    MonsterHoleView.super.ctor(self, resource)
end

function MonsterHoleView:start()
    self._btnFight.onClick:AddListener(handler(self, self._onBtnFightClick))
    self._btnClose.onClick:AddListener(handler(self, self._onBtnCloseClick))
    self._btnTeam.onClick:AddListener(handler(self, self._onBtnTeamClick))

    self._listDrop:SetTemplate(
        handler(self, self._onDropUpdate),
        handler(self._onDropValueChange),
        handler(self, self._onDropTouch)
    )
    self._selectedId = monsterhole.indexOf(1).id
    self._listHole:SetTemplate(
        handler(self, self._onItemUpdate),
        handler(self, self._onValueChange),
        handler(self, self._onItemTouch)
    )
    self._listHole:ReSize(monsterhole.length())
    self._signalId = G_SignalManager:beginCache()
    G_SignalManager:add(SignalConst.EVENT_GAME_ENTER_SCENE, handler(self, self._onEventGameEnterScene))
    G_SignalManager:endCache()
    self:_updateView()
end

function MonsterHoleView:onDestroy()
    G_SignalManager:removeCache(self._signalId)
end

function MonsterHoleView:_onEventGameEnterScene()
    self:close()
end

function MonsterHoleView:_onItemUpdate(item, index)
    local startIndex = index + 1
    local cfg = monsterhole.indexOf(startIndex)
    item:updateUI(cfg, self._selectedId)
end

function MonsterHoleView:_onValueChange()
end

function MonsterHoleView:_onItemTouch(item, id)
    self._selectedId = id
    self._listHole:UpdateUsedCell()
    self:_updateView()
end

function MonsterHoleView:_updateView()
    local cfg = monsterhole.get(self._selectedId)
    self._textName.text = cfg.name
    self._textDesc.text = cfg.desc
    self._drops = DropHelper.getDrops(cfg.drop)
    self._listDrop:ReSize(#self._drops)
end

function MonsterHoleView:_onDropUpdate(item, index)
    local startIndex = index + 1
    item:updateUI(self._drops[startIndex])
end

function MonsterHoleView:_onDropValueChange()
end

function MonsterHoleView:_onDropTouch()
end

function MonsterHoleView:_onBtnFightClick()
    self:close()
    local cfg = monsterhole.get(self._selectedId)
    G_SceneManager:loadSceneAnsc(cfg.scene)
end

function MonsterHoleView:_onBtnCloseClick()
    self:close()
end

function MonsterHoleView:_onBtnTeamClick()
    G_UserData:getTeamGroup():c2sCreateTeam(self._selectedId)
end

return MonsterHoleView
